<template>
  <el-dialog title="人员选择-多选" :visible="visible" width="1250px" append-to-body @close="close">
    <el-container class="list-container">
      <el-aside width="auto" class="aside">
        <el-button type="primary" @click="removeUser">移除</el-button>
        <el-button type="primary" @click="confirm">确定</el-button>
        <el-table
          v-loading="loading"
          :data="selectedData"
          style="width: 100%"
          highlight-current-row
          border
          @selection-change="handleSelectionSelectedChange"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column
            v-for="(item, index) in showCols"
            :key="index"
            :label="item.label"
            :prop="item.prop"
            :show-overflow-tooltip="item.showOverflowTooltip"
            :width="item.width"
            :formatter="item.formatFunc"
            :sortable="item.sortable"
          />
        </el-table>
      </el-aside>

      <el-container class="tab-container">
        <el-aside width="auto" class="aside">
          <el-tree
            ref="tree"
            class="aside-tree"
            :data="treeData"
            node-key="id"
            :default-expanded-keys="cacheTreeExpandedKeys"
            @current-change="handleTreeSelectChange"
            @node-expand="handleNodeExpand"
            @node-collapse="handleNodeCollapse"
          />
        </el-aside>
        <el-main class="main" style="margin:0">
          <collapse-tab class="main-search">
            <el-form
              :inline="true"
              :model="queryCondition"
              label-width="80px"
              @keyup.enter.native="query"
            >
              <!--查询条件区 -->
              <el-form-item label="姓名">
                <p-input v-model="queryCondition.name" class="form-item" />
              </el-form-item>
              <el-form-item label="账号">
                <p-input v-model="queryCondition.account" class="form-item" />
              </el-form-item>
              <el-form-item>
                <el-checkbox v-model="queryCondition.ignoreParent">查询全部</el-checkbox>
              </el-form-item>
              <el-form-item style="float:right;">
                <list-button-query :page-code="pageCode" />
              </el-form-item>
              <div class="clearfix" />
            </el-form>
          </collapse-tab>
          <el-card class="main-report">
            <div>
              <el-button type="primary" @click="addUser">添加</el-button>

              <div style="clear:both;" />
            </div>
            <div style="margin-top:5px;">
              <div>
                <columns-controller v-model="columnList" :table-key="tableKey" />
              </div>
              <el-table
                v-loading="loading"
                :data="tableData"
                style="width: 100%"
                highlight-current-row
                border
                @sort-change="handleSortChange"
                @selection-change="handleSelectionChange"
              >
                <el-table-column type="selection" width="55" />
                <el-table-column
                  v-for="(item, index) in showCols"
                  :key="index"
                  :label="item.label"
                  :prop="item.prop"
                  :show-overflow-tooltip="item.showOverflowTooltip"
                  :width="item.width"
                  :formatter="item.formatFunc"
                  :sortable="item.sortable"
                />
              </el-table>
            </div>
            <list-pager
              :page-num="pageInfo.pageNum"
              :page-size="pageInfo.pageSize"
              :page-total="pageTotal"
            />
          </el-card>
        </el-main>
      </el-container>
    </el-container>
  </el-dialog>
</template>

<script>
import CollapseTab from '@/components/CollapseTab'
import ColumnsController from '@/components/ColumnsController'
import PInput from '@/components/popsoft/Query/PInput'
import ListButtonQuery from '@/components/popsoft/Button/ListButtonQuery'
import ListPager from '@/components/popsoft/Page/ListPager'

const MODULE_CODE = 'system'
const ENTITY_TYPE = 'user'
export default {
  name: 'userSingleSelect',
  components: {
    CollapseTab,
    ColumnsController,
    PInput,
    ListButtonQuery,
    ListPager

  },
  data() {
    return {
      // 加载中
      loading: false,
      // 表格数据
      tableData: [],
      // 当前行
      currentId: this.constant.NO_ITEM_SELECTED,
      // 总页数
      pageTotal: 0,
      // 分页信息
      pageInfo: {
        // 页码
        pageNum: this.constant.DEFAULT_PAGE_NUM,
        // 页码大小
        pageSize: this.constant.DEFAULT_PAGE_SIZE
      },
      // 排序信息
      sortInfo: {
        sort_field: 'orderNo',
        sort_sortType: 'ascending'
      },
      // 复选框选中项
      multipleSelection: [],

      entityType: ENTITY_TYPE,
      moduleCode: MODULE_CODE,
      // eslint-disable-next-line no-eval
      api: eval('this.$api.' + MODULE_CODE + '.' + ENTITY_TYPE),
      apiTree: this.$api.system.organization,
      pageCode: MODULE_CODE + ':' + ENTITY_TYPE + ':',
      queryCondition: {
        parentId: '',
        organizationId: ''
      },
      columnList: [
        { prop: 'name', label: '姓名', show: true },
        { prop: 'account', label: '账号', show: true },
        { prop: 'organizationName', label: '组织机构', show: true, showOverflowTooltip: true }

      ],
      // 已设置人员列表的复选框选中项
      multipleSelectionSelected: [],
      treeData: null,
      cacheTreeExpandedKeys: [this.constant.DEFAULT_EXPANDED_ID],

      isRefreshTree: false,
      parentId: '',
      parentName: '',
      visible: false,
      // 已选择的用户
      selectedData: []

    }
  },
  computed: {
    showCols() {
      return this.columnList.filter(item => item.show)
    },
    tableKey() {
      const { path } = this.$route
      return `${path}/table`
    }
  },
  watch: {
    parentId() {
      this.queryCondition.organizationId = this.parentId
    }
  },
  mounted() {
    this.loadData()
  },
  methods: {
    show(value) {
      this.loadData()
      // 加载已设置的人员
      this.api.getUser({ idList: value })
        .then(res => {
          this.selectedData = res.data
        }).finally(() => {
          this.loading = false
        })

      this.visible = true
    },
    confirm() {
      this.$emit('ok', this.selectedData)
      this.visible = false
    },
    close() {
      this.visible = false
    },
    removeUser() {
      if (this.multipleSelectionSelected.length === 0) {
        this.$message({
          type: 'info',
          message: '请至少选择一行'
        })
        return
      }

      this.multipleSelectionSelected.forEach((item, index) => {
        this.selectedData.splice(index, 1)
      })
    },
    handleSelectionSelectedChange(value) {
      this.multipleSelectionSelected = value
    },
    addUser() {
      if (this.multipleSelection.length === 0) {
        this.$message({
          type: 'info',
          message: '请至少选择一行'
        })
        return
      }

      const selectedIdList = this.selectedData.map(x => x.id)
      const that = this
      this.multipleSelection.forEach(function (item) {
        if (!selectedIdList.find(value => value === item.id)) {
          that.selectedData.push(item)
        }
      })
    },
    // 初始化
    loadData() {
      this.getTreeAndTableData()
    },
    // 获取表格数据
    getTableData() {
      this.loading = true
      const params = Object.assign(this.queryCondition, this.pageInfo, this.sortInfo)
      this.api.page(params)
        .then(res => {
          this.tableData = res.data.records
          this.pageTotal = res.data.total
        }).finally(() => {
          this.loading = false
          this.currentId = this.constant.NO_ITEM_SELECTED
        })
    },
    // 处理分页
    handlePage(value) {
      this.pageInfo.pageNum = value
      this.refresh()
    },
    // 处理分页大小
    handlePageSize(value) {
      this.pageInfo.pageSize = value
      this.refresh()
    },
    // 处理排序
    // eslint-disable-next-line no-unused-vars
    handleSortChange({ column, prop, order }) {
      this.sortInfo.sort_field = prop
      this.sortInfo.sort_sortType = order
      this.refresh()
    },
    // 复选多行
    handleSelectionChange(val) {
      this.multipleSelection = val
    },

    // 处理查询
    query() {
      // 查询之前，将当前页置为1
      this.pageInfo.pageNum = 1
      this.refresh()
    },

    // 查看
    view(id) {
      this.$refs.detail.view(id)
    },

    // 刷新
    refresh() {
      this.getTableData()
    },
    // 判断是否选中行 ,尚未使用
    checkRowSelected() {
      if (this.currentId === this.constant.NO_ITEM_SELECTED) {
        this.$message.info('请先选中一行')
        return false
      }
      return true
    },
    // 获取表格选中行id
    getCheckedId() {
      let ids = ''
      this.multipleSelection.forEach(function (item) {
        ids += item.id + ','
      })
      return ids
    },

    // 树表相关操作
    handleTreeSelectChange(data) {
      this.queryCondition.parentId = data.id
      this.pageInfo.pageNum = 1

      // 保存标识及名称用于新增操作
      this.parentId = data.id
      this.parentName = data.label
      this.getTableData()
    },
    // 获取树，再获取表格
    getTreeAndTableData() {
      this.apiTree.tree()
        .then(res => {
          this.treeData = res.data

          // 如没有默认选中节点
          if (this.queryCondition.parentId === '') {
            // 默认设置根节点
            this.queryCondition.parentId = this.treeData[0].id
            this.parentId = this.treeData[0].id
            this.parentName = this.treeData[0].label

            // 设置根节点默认展开
            this.cacheTreeExpandedKeys.push(this.treeData[0].id)
          }
          this.getTableData()
        })
    },
    // 展开树节点
    handleNodeExpand(data) {
      this.cacheTreeExpandedKeys.push(data.id)
    },
    // 折叠树节点
    handleNodeCollapse(data) {
      const index = this.cacheTreeExpandedKeys.findIndex(item => item === data.id)
      this.cacheTreeExpandedKeys.splice(index, 1)
    }

  }
}
</script>

  <style lang="scss">
.tab-container {
  .main .main-search {
    .el-form-item {
      margin-bottom: 5px;
    }
  }
}
</style>
  <style lang="scss" scoped>
.tab-container {
  $item-width: 200px;
  padding: 15px;
  .aside {
    min-width: 180px;
    background-color: white;
  }
  .main {
    .main-search {
      .form-item {
        width: $item-width;
      }
    }
    .main-report {
      margin-top: 10px;
    }
  }
}
</style>
